package cn.cdeden.knowledge.service.impl;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.StringUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.*;
import cn.cdeden.knowledge.domain.dto.*;
import cn.cdeden.knowledge.domain.enums.DateUtilEnums;
import cn.cdeden.knowledge.domain.enums.MessageTypeEnums;
import cn.cdeden.knowledge.domain.vo.SysCalendarVO;
import cn.cdeden.knowledge.enums.MessageFileTypeEnums;
import cn.cdeden.knowledge.mapper.SysCalendarMapper;
import cn.cdeden.knowledge.mapper.SysCalendarSharingMapper;
import cn.cdeden.knowledge.service.*;
import cn.cdeden.knowledge.utils.DateUtil;
import cn.cdeden.knowledge.utils.PageUtil;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.domain.vo.RemoteUserVo;
import cn.cdeden.system.api.domain.vo.RemoteUserFeedBackVO;
import cn.cdeden.system.api.model.LoginUser;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
* @author Yu.
* @date 2023-02-02
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = SysCalendarService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SysCalendarServiceImpl extends ServiceImpl<SysCalendarMapper, SysCalendar> implements SysCalendarService {

    // private final RedisUtils redisUtils;
    private final SysCalendarMapper sysCalendarMapper;
    private final SysCalendarSharingMapper sysCalendarSharingMapper;
    private final SysMessageService sysMessageService;
    @DubboReference
    private final RemoteUserService remoteUserService;
    private final SysCalendarFeedBackService sysCalendarFeedBackService;
//    private final SysResourcePlanService sysResourcePlanService;
//    private final RabbitTemplate rabbitTemplate;
    private final SysCalendarMessageService sysCalendarMessageService;
    private final SysCalendarWorkService sysCalendarWorkService;
//    private final ProjectTaskService projectTaskService;

//    private final FrmMeetingService frmMeetingService;




    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public TableDataInfo<SysCalendarDto> queryAll(SysCalendarQueryParam query, Pageable pageable) {
        IPage<SysCalendar> queryPage = PageUtil.toMybatisPage(pageable);
        String dateType = query.getDateType();
        DateUtilEnums utilEnums = DateUtilEnums.find(dateType);

        if (ObjectUtils.isEmpty(utilEnums)){
            throw new RuntimeException("错误的类型");
        }

        QueryWrapper<SysCalendar> queryWrapper =  new QueryWrapper<SysCalendar>();

        String startDateStr = DateUtil.localDateTimeFormat(DateUtil.toLocalDateTime(query.getStartDate()), utilEnums.getTextJava());

        String endDateStr = DateUtil.localDateTimeFormat(DateUtil.toLocalDateTime(query.getEndDate()), utilEnums.getTextJava());
        queryWrapper.apply("date_format(start_date, '"+utilEnums.getTextSql()+"')  BETWEEN  {0} and {1} ", startDateStr , endDateStr );
        queryWrapper.or().apply("date_format(end_date, '"+utilEnums.getTextSql()+"')  BETWEEN  {0} and {1} ", startDateStr, endDateStr);

        IPage<SysCalendar> page = sysCalendarMapper.selectPage(queryPage, queryWrapper);
        TableDataInfo<SysCalendar> build = TableDataInfo.build(page);
        return MapstructUtils.convertTableDataInfo(build, SysCalendarDto.class);
    }

    @Override
    public List<SysCalendarDto> queryAll(SysCalendarQueryParam query){
        LoginUser user = LoginHelper.getLoginUser();//用户信息
        query.setUserId(user.getUserId());
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localStartDate = query.getStartDate().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        String startTime = localStartDate.format(dateTimeFormatter);
        LocalDate localEndDate = query.getEndDate().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        String endTime = localEndDate.format(dateTimeFormatter);
        List<SysCalendarDto> calendarList = sysCalendarMapper.getCalendarList(user.getUserId(), startTime, endTime, query.getType(), query.getScheduleId());
        calendarList.forEach(v -> {
            String userIds = v.getUserIdList();
            JSONArray jsonArray = JSONUtil.parseArray(userIds);
            List<Integer> userIdList = jsonArray.stream()
                    .map(Object::toString)
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            if (!userIdList.isEmpty()) {
                List<RemoteUserFeedBackVO> userAndFeedBack = remoteUserService.getUserAndFeedBack(v.getId(), userIdList);
                userAndFeedBack.forEach(value -> {
                    if (value.getFeedBack() == null) {
                        value.setFeedBack("tentative");
                    }
                });
                v.setUserList(remoteUserService.getUserAndFeedBack(v.getId(), userIdList));
            }
            if (userIdList.isEmpty()) {
                List<RemoteUserFeedBackVO> sysUserList = new ArrayList<>();
                v.setUserList(sysUserList);
            }
            SysCalendarFeedBack sysCalendarFeedBack = sysCalendarFeedBackService.getOne(new QueryWrapper<SysCalendarFeedBack>().eq("user_id", user.getUserId()).eq("calendar_id", v.getId()));
            if (sysCalendarFeedBack == null) {
                SysCalendarFeedBack sysCalendarFeedBack2 = new SysCalendarFeedBack();
                sysCalendarFeedBack2.setFeedBack("tentative");
                sysCalendarFeedBack2.setCalendarId(v.getId());
                sysCalendarFeedBack2.setUserId(user.getUserId());
                v.setSysCalendarFeedBack(sysCalendarFeedBack2);
            }
        });
        //日历中加入我的工时的数据
//        List<Map<String, Object>> myWorkList = new ArrayList<>();
//        if (!query.getType().equals("schedule")) {
//            myWorkList = projectTaskService.queryMyTaskCalendar(query.getStartDate(), query.getEndDate(), Long.toString(user.getId()));
//        }

//        List<SysCalendarDto> sysCalendarDtoList = new ArrayList<>();
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
//        myWorkList.forEach(map -> {
//            try {
//                Date startDate = parseDate((String) map.get("startDate"), true);
//                Date endDate = parseDate((String) map.get("endDate"), false);
//
//                SysCalendarDto sysCalendarDto = SysCalendarDto.builder()
//                        .myTaskId((String) map.get("id"))
//                        .label((String) map.get("label"))                 // 设置标签
//                        .content((String) map.get("content"))             // 设置内容
//                        .startDate(startDate)                            // 设置开始时间
//                        .endDate(endDate)// 设置结束时间
//                        .category("task")
//                        .projectId((String) map.get("F_PRJID"))
//                        .build();
//                sysCalendarDtoList.add(sysCalendarDto);
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//        });
//        calendarList.addAll(sysCalendarDtoList);
        calendarList.forEach(v -> {
            if (v.getCategory() == null || v.getCategory().isEmpty()) {
                v.setCategory("calendar");
            }
        });

        // 会议
//        List<SysCalendarDto> sysCalendarDtos = new ArrayList<>();
//        List<FrmMeetingDto> frmMeetingDtos = frmMeetingService.queryMyMeetings(query.getStartDate(), query.getEndDate(), Long.toString(user.getId()));
//        frmMeetingDtos.stream().forEach(v -> {
//            SysCalendarDto sysCalendarDto = SysCalendarDto.builder()
//                .myTaskId(v.getId().toString())
//                .label((String) v.getMeetName())                 // 设置标签
//                .content((String) v.getMeetTitle())             // 设置内容
//                .startDate(v.getBeginTime())                            // 设置开始时间
//                .endDate(v.getEndTime())// 设置结束时间
//                .category("meeting")
//                .build();
//            sysCalendarDtos.add(sysCalendarDto);
//                }
//
//        );

//        calendarList.addAll(sysCalendarDtos);

        return calendarList;
    }

    // 日期解析方法，处理转换异常
    private Date parseDate(String dateStr, boolean isStartDate) throws ParseException {
        if (dateStr == null || dateStr.isEmpty()) {
            return null;
        }
        String timeStr = isStartDate ? "00:00:00" : "23:59:59";
        String formattedDateStr = dateStr + " " + timeStr;
        return DATE_TIME_FORMAT.parse(formattedDateStr);
    }

    @Override
    public TableDataInfo<SysCalendarDto> queryPageAll(SysCalendarQueryParam query, Pageable pageable) {
        IPage<SysCalendar> queryPage = PageUtil.toMybatisPage(pageable);
        LoginUser user = LoginHelper.getLoginUser();//用户信息
        query.setUserId(user.getUserId());

        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startDateStr = sdf.format(query.getStartDate());
        String endDateStr = sdf.format(query.getEndDate());
        String toDateStr = sdf.format(new Date());
        IPage<SysCalendar> sysCalendarDtoIPage = sysCalendarMapper.queryPageAll(query, queryPage, startDateStr, endDateStr, toDateStr);
        TableDataInfo<SysCalendar> build = TableDataInfo.build(sysCalendarDtoIPage);
        return MapstructUtils.convertTableDataInfo(build, SysCalendarDto.class);
    }

    @Override
    public SysCalendar getById(Long id) {
        return sysCalendarMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public SysCalendarDto findById(Long id) {
        return MapstructUtils.convert(getById(id), SysCalendarDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insert(SysCalendarDto resources) {
        //新建日程时如果添加了资源则需要对资源安排表中的数据进行添加（注意添加的时候进行判断，如果资源在这个时间段已经被占用了则不能成功创建这个日程）
//        List<SysResourcePlan> sysResourcePlanList = new ArrayList<>();
//        Date startDate = resources.getStartDate();
//        Date endDate = resources.getEndDate();
        //计算出消息在RabbitMQ中存活的时间
//        long remindTimeInMillis = TimeUnit.MINUTES.toMillis(resources.getRemindTime());
//        long messageSendTime = startDate.getTime() - remindTimeInMillis;
//        long currentTimeMillis = new Date().getTime();
//        long messageLifetimeMillis = messageSendTime -currentTimeMillis;
//        if (messageLifetimeMillis < 0) {
//            messageLifetimeMillis = 0;
//        }
//        LocalDateTime localDateTime = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
//        LocalDateTime localDateTime1 = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
//        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String startTime = localDateTime.format(dateTimeFormatter);
//        String endTime = localDateTime1.format(dateTimeFormatter);
//        if (resources.getResourceIds() != null && !resources.getResourceIds().isEmpty() ) {
//            List<SysResourcePlan> sysResourcePlans = sysResourcePlanService.list(
//                    new QueryWrapper<SysResourcePlan>()
//                            .in("resource_id", resources.getResourceIds())
//                            .and(wrapper -> wrapper
//                                    .or(w -> w.between("resource_start_time", startTime, endTime))
//                                    .or(w -> w.between("resource_end_time", startTime, endTime))
//                                    .or(w -> w.le("resource_start_time", startTime).ge("resource_end_time", startTime))
//                                    .or(w -> w.le("resource_start_time", endTime).ge("resource_end_time", endTime))
//                            )
//            );
//            if (!sysResourcePlans.isEmpty()) {
//                return false;
//            }
//        }
//        if (resources.getResourceIds() !=null && !resources.getResourceIds().isEmpty()) {
//            resources.getResourceIds().forEach(v -> {
//                SysResourcePlan sysResourcePlan = new SysResourcePlan();
//                sysResourcePlan.setResourceId(v);
//                sysResourcePlan.setResourceEndTime(resources.getEndDate());
//                sysResourcePlan.setResourceStartTime(resources.getStartDate());
//                sysResourcePlanList.add(sysResourcePlan);
//            });
//            sysResourcePlanService.saveBatch(sysResourcePlanList);
//        }
        LoginUser user = LoginHelper.getLoginUser();

        SysCalendar entity = MapstructUtils.convert(resources, SysCalendar.class);
        if (StringUtils.isEmpty(entity.getCreateId())) {
            entity.setCreateId(String.valueOf(user.getUserId()));
        }
        if (StringUtils.isEmpty(entity.getCreateBy())) {
            entity.setCreateBy(user.getNickname());
        }
        if (entity.getCreateTime() == null) {
            entity.setCreateTime(new Date());
        }
        if (StringUtils.isEmpty(entity.getUpdateId())) {
            entity.setUpdateId(String.valueOf(user.getUserId()));
        }
        if (StringUtils.isEmpty(entity.getUpdateBy())) {
            entity.setUpdateBy(user.getNickname());
        }
        entity.setResourceId(new JSONArray(resources.getResourceIds()).toString());
        this.save(entity);


        //日程个人工时
        List<SysCalendarWork> sysCalendarWorkList = new ArrayList<>();
        resources.getUserIds().forEach(v -> {
            SysCalendarWork sysCalendarWork = new SysCalendarWork();
            sysCalendarWork.setCalendarId(entity.getId());
            sysCalendarWork.setUserId(v.longValue());
            sysCalendarWork.setWorkHours(resources.getWorkHours());
            sysCalendarWorkList.add(sysCalendarWork);
        });
        sysCalendarWorkService.saveBatch(sysCalendarWorkList);

        SysCalendarMessage sysCalendarMessage = new SysCalendarMessage();
        sysCalendarMessage.setCalendarId(entity.getId());
        sysCalendarMessage.setCreateTime(new Date());
        sysCalendarMessageService.save(sysCalendarMessage);

        SendCalendarMessageVO sendCalendarMessageVO = new SendCalendarMessageVO();
        sendCalendarMessageVO.setCalendarMessageId(sysCalendarMessage.getCalendarMessageId());
        sendCalendarMessageVO.setCalendarId(entity.getId());


        SysCalendarSharing sysCalendarSharing = new SysCalendarSharing();
        sysCalendarSharing.setCalendarSharingId(new JSONArray(resources.getUserIds()).toString());
        sysCalendarSharing.setCalendarId(entity.getId());
        sysCalendarSharingMapper.insert(sysCalendarSharing);

        List<String> toUserIds = resources.getUserIds().stream().map(Object::toString).collect(Collectors.toList());
        String sendId = user.getUserId().toString();
        toUserIds.removeIf(v -> v.equals(sendId));

        for (String toUserId : toUserIds) {
            //创建消息
            SysMessageDto sysMessageDto = new SysMessageDto();
            sysMessageDto.setContent(user.getNickname()+"与你共享了一个日历");
            sysMessageDto.setOperator(user.getUserId().toString());
//            sysMessageDto.setNodeId(parentTreeNodeAll.get(i).getId().toString());
            sysMessageDto.setMessageType("1");
            sysMessageDto.setFileType(MessageFileTypeEnums.CALENDAR.getCode());
            sysMessageDto.setType(MessageTypeEnums.ADD.getCode());
            sysMessageDto.setRecipient(toUserId);
            sysMessageService.addMessage(sysMessageDto);
        }



//        messageUtils.createList(MessageTypeChildEnums.CALENDAR_SHARING, user.getId().toString(), user.getId().toString(), toUserIds,
//                user.getUsername()+"与你共享了一个日历");
//        long finalMessageLifetimeMillis = messageLifetimeMillis;
//        rabbitTemplate.convertAndSend(RabbitmqConfig.ECM_CALENDAR_EXCHANGE, RabbitmqConfig.ECM_CALENDAR_DELAY_ROUTING, sendCalendarMessageVO, m -> {
//            m.getMessageProperties().setExpiration(String.valueOf(finalMessageLifetimeMillis));
//            m.getMessageProperties().setDeliveryMode(MessageProperties.DEFAULT_DELIVERY_MODE.PERSISTENT);
//            return m;
//        });
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(SysCalendarDto resources){
        SysCalendar entity = MapstructUtils.convert(resources, SysCalendar.class);
        entity.setWorkHours(null);
        Date startDate = entity.getStartDate();
        sysCalendarSharingMapper.delete(new QueryWrapper<SysCalendarSharing>().eq("calendar_id", resources.getId()));
        SysCalendarSharing sysCalendarSharing = new SysCalendarSharing();
        sysCalendarSharing.setCalendarId(entity.getId());
        sysCalendarSharing.setCalendarSharingId(new JSONArray(resources.getUserIds()).toString());
        sysCalendarSharingMapper.insert(sysCalendarSharing);
        boolean ret = this.updateById(entity);
        LoginUser user = LoginHelper.getLoginUser();
        sysCalendarWorkService.update(new UpdateWrapper<SysCalendarWork>().eq("calendar_id", entity.getId()).eq("user_id", user.getUserId()).set("work_hours", resources.getWorkHours()));
        boolean remove = sysCalendarMessageService.remove(new QueryWrapper<SysCalendarMessage>().eq("calendar_id", resources.getId()));
        SysCalendarMessage sysCalendarMessage = new SysCalendarMessage();
        sysCalendarMessage.setCalendarId(entity.getId());
        sysCalendarMessage.setCreateTime(new Date());
        sysCalendarMessageService.save(sysCalendarMessage);

        SysCalendar sysCalendar = this.getOne(new QueryWrapper<SysCalendar>().eq("id", resources.getId()));
        if (sysCalendar != null && sysCalendar.getRemindTime() != null && resources.getRemindTime() != null && !sysCalendar.getRemindTime().equals(resources.getRemindTime())) {
            Date startDate1 = resources.getStartDate();
            Date endDate = resources.getEndDate();
            long remindTimeInMillis = TimeUnit.MINUTES.toMillis(resources.getRemindTime());
            long messageSendTime = startDate1.getTime() - remindTimeInMillis;
            long currentTimeMillis = new Date().getTime();
            long messageLifetimeMillis = messageSendTime -currentTimeMillis;
            if (messageLifetimeMillis < 0) {
                messageLifetimeMillis = 0;
            }
            SysCalendarMessage sysCalendarMessage1 = new SysCalendarMessage();
            sysCalendarMessage1.setCalendarId(resources.getId());
            sysCalendarMessage1.setCreateTime(new Date());
            sysCalendarMessageService.save(sysCalendarMessage1);
            SendCalendarMessageVO sendCalendarMessageVO = new SendCalendarMessageVO();
            sendCalendarMessageVO.setCalendarMessageId(sysCalendarMessage1.getCalendarMessageId());
            sendCalendarMessageVO.setCalendarId(resources.getId());
            long finalMessageLifetimeMillis = messageLifetimeMillis;
//            rabbitTemplate.convertAndSend(RabbitmqConfig.ECM_CALENDAR_EXCHANGE, RabbitmqConfig.ECM_CALENDAR_DELAY_ROUTING, sendCalendarMessageVO, m -> {
//                m.getMessageProperties().setExpiration(String.valueOf(finalMessageLifetimeMillis));
//                m.getMessageProperties().setDeliveryMode(MessageProperties.DEFAULT_DELIVERY_MODE.PERSISTENT);
//                return m;
//            });
        }
//        SendCalendarMessageVO sendCalendarMessageVO = new SendCalendarMessageVO();
//        sendCalendarMessageVO.setCalendarId(entity.getId());
//        sendCalendarMessageVO.setCalendarMessageId(sysCalendarMessage.getCalendarMessageId());
//        if (resources.getRemindTime() != null) {
//            long remindTimeInMillis = TimeUnit.MINUTES.toMillis(resources.getRemindTime());
//            long messageSendTime = startDate.getTime() - remindTimeInMillis;
//            long messageLifetimeMillis = messageSendTime - new Date().getTime();
//            if (messageLifetimeMillis < 0) {
//                messageLifetimeMillis = 0;
//            }
//            long finalMessageLifetimeMillis = messageLifetimeMillis;
//            rabbitTemplate.convertAndSend(RabbitmqConfig.ECM_CALENDAR_EXCHANGE, RabbitmqConfig.ECM_CALENDAR_DELAY_ROUTING, sendCalendarMessageVO, m -> {
//                m.getMessageProperties().setExpiration(String.valueOf(finalMessageLifetimeMillis));
//                m.getMessageProperties().setDeliveryMode(MessageProperties.DEFAULT_DELIVERY_MODE.PERSISTENT);
//                return m;
//            });
//        }
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(Set<Long> ids){
        // delCaches(ids);
        Long calendarId = ids.iterator().next();
        SysCalendar sysCalendar = sysCalendarMapper.selectById(calendarId);
        LoginUser user = LoginHelper.getLoginUser();//用户信息
        if (!sysCalendar.getCreateId().equals( user.getUserId().toString())) {
            throw new RuntimeException("无权删除");
        }
        return this.removeByIds(ids);
    }

    @Override
    public SysCalendarVO getWeekly(String startTime, String username) {
        RemoteUserVo user = remoteUserService.selectUserByUserName(username);//用户信息
        String[] dayStrings = {"one", "two", "three", "four", "five", "six", "seven"};
        if (startTime == null) {
            Date currentTime = new Date();
            Calendar instance = Calendar.getInstance();
            instance.setTime(currentTime);
            int dayOfWeek = instance.get(Calendar.DAY_OF_WEEK);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            List<String> datesFromMondayToToday = new ArrayList<>();
            int daysToMonday = (dayOfWeek == Calendar.SUNDAY) ? 6 : dayOfWeek - Calendar.MONDAY;
            instance.add(Calendar.DAY_OF_MONTH, -daysToMonday);
            for (int i = 0; i <= daysToMonday; i++) {
                datesFromMondayToToday.add(dateFormat.format(instance.getTime()));
                instance.add(Calendar.DAY_OF_MONTH, 1);
            }
            Map<String, Object> map = new LinkedHashMap<>(16);
            for (int i = 0; i < datesFromMondayToToday.size(); i++) {
                List<String> weekly = getBaseMapper().getWeekly(datesFromMondayToToday.get(i), user.getUserId());
                map.put(dayStrings[i], weekly);
            }
            int size = map.size();
            for (int j = size; j < dayStrings.length; j++) {
                map.put(dayStrings[j], new ArrayList<>());
            }
            SysCalendarVO sysCalendarVO = new SysCalendarVO();
            sysCalendarVO.setName(user.getNickName());
            sysCalendarVO.setCurrentDate(dateFormat.format(currentTime));
            sysCalendarVO.setWeeklyWork(map);

            return sysCalendarVO;
        }
        Map<String, Object> map = new LinkedHashMap<>(16);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate parse = LocalDate.parse(startTime, dateTimeFormatter);
        for (int i =0 ; i<7; i++) {
            LocalDate localDate = parse.plusDays(i);
            List<String> weekly = getBaseMapper().getWeekly(localDate.format(dateTimeFormatter), user.getUserId());
            map.put(dayStrings[i], weekly);
        }
        int size = map.size();
        for (int j = size; j < dayStrings.length; j++) {
            map.put(dayStrings[j], new ArrayList<>());
        }
        SysCalendarVO sysCalendarVO = new SysCalendarVO();
        sysCalendarVO.setName(user.getNickName());
        sysCalendarVO.setCurrentDate(startTime);
        sysCalendarVO.setWeeklyWork(map);
        return sysCalendarVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean fromMissionToCalenadr(MissionToCalendarDTO missionToCalendarDTO) {
        SysCalendar sysCalendar = MapstructUtils.convert(missionToCalendarDTO, SysCalendar.class);
        sysCalendar.setMission("true");
        sysCalendar.setMissionId(missionToCalendarDTO.getMissionId());
        this.save(sysCalendar);
        //日程分享表中插入数据
        SysCalendarSharing sysCalendarSharing = new SysCalendarSharing();
        sysCalendarSharing.setCalendarId(sysCalendar.getId());
        sysCalendarSharing.setCalendarSharingId(new JSONArray(missionToCalendarDTO.getUserIds()).toString());
        sysCalendarSharingMapper.insert(sysCalendarSharing);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMissionCalendar(MissionToCalendarDTO missionToCalendarDTO) {
        SysCalendar sysCalendar = MapstructUtils.convert(missionToCalendarDTO, SysCalendar.class);
        Boolean aBoolean = true;
        aBoolean = getBaseMapper().updateMissionCalendar(missionToCalendarDTO);
        SysCalendar sysCalendar1 = sysCalendarMapper.selectOne(new QueryWrapper<SysCalendar>().eq("mission_id", missionToCalendarDTO.getMissionId()).select("id"));
        SysCalendarSharing sysCalendarSharing = new SysCalendarSharing();
        sysCalendarSharing.setCalendarId(sysCalendar1.getId());
        sysCalendarSharing.setCalendarSharingId(new JSONArray(missionToCalendarDTO.getUserIds()).toString());
        int update = sysCalendarSharingMapper.update(sysCalendarSharing, new UpdateWrapper<SysCalendarSharing>().eq("calendar_id", sysCalendarSharing.getCalendarId()).set("calendar_sharing_id", sysCalendarSharing.getCalendarSharingId()));
        if (update < 1) {
            aBoolean = false;
        }
        return aBoolean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeMissionCalendar(Long missionId) {
        Boolean aBoolean = true;
        int missionTotal = sysCalendarMapper.delete(new QueryWrapper<SysCalendar>().eq("mission_id", missionId));
        if (missionTotal < 1) {
            aBoolean = false;
        }
        SysCalendar sysCalendar = sysCalendarMapper.selectOne(new QueryWrapper<SysCalendar>().eq("mission_id", missionId).select("id"));
        int calendarTotal = sysCalendarSharingMapper.delete(new QueryWrapper<SysCalendarSharing>().eq("calendar_id", sysCalendar.getId()));
        if (calendarTotal < 1) {
            aBoolean = false;
        }
        return aBoolean;
    }

    @Override
    public List<SysCalendar> getDetailShow(Long calendarId) {
        return getBaseMapper().getDetailShow(calendarId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Long id){
        Set<Long> set = new HashSet<>(1);
        set.add(id);
        return this.deleteByIds(set);
    }

    /*
    private void delCaches(Long id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Long> ids) {
        for (Long id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<SysCalendarDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (SysCalendarDto sysCalendar : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("标签", sysCalendar.getLabel());
              map.put("内容", sysCalendar.getContent());
              map.put("类型", sysCalendar.getCalendarType());
              map.put("颜色代码", sysCalendar.getCalendarColor());
              map.put("优先级", sysCalendar.getCalendarPriority());
              map.put("开始时间", sysCalendar.getStartDate());
              map.put("结束时间", sysCalendar.getEndDate());
              map.put("拥有者编号", sysCalendar.getCreateId());
              map.put("创建者", sysCalendar.getCreateBy());
              map.put("创建日期", sysCalendar.getCreateTime());
              map.put("更新编号", sysCalendar.getUpdateId());
              map.put("更新者", sysCalendar.getUpdateBy());
              map.put("更新时间", sysCalendar.getUpdateTime());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/
}
